package com.hongdee.crm.average.service.impl;

import com.hongdee.common.dao.IHibernateDao;
import com.hongdee.crm.average.dao.IAverageDao;
import com.hongdee.crm.average.entity.TCrmAverageCarEntity;
import com.hongdee.crm.average.service.ITCrmIAverageCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dell on 2017/6/2.
 */
@Service
public class TCrmIAverageCarServiceImpl implements ITCrmIAverageCarService {
    @Autowired
    private IAverageDao iAverageDao;
    private  String tabName="T_CRM_AVERAGE_CAR";
    @Autowired
    private IHibernateDao iHibernateDao;

    /*
     * 停用启用
     * */
    @Override
    public void update(String id, String status) throws Exception {
        String hql = "update T_CRM_AVERAGE_CAR set status = :status where id = :id ";
        Map params = new HashMap();
        params.put("id", id);
        params.put("status", status);
        this.iAverageDao.update(hql, params);
    }

    @Override
    public TCrmAverageCarEntity saveOrUpdate(TCrmAverageCarEntity tCrmAverageCarEntity) throws Exception {
        int carNum = Integer.valueOf(tCrmAverageCarEntity.getBaseCar());
        int loss = Integer.valueOf(tCrmAverageCarEntity.getLoss());
        int ins = Integer.valueOf(tCrmAverageCarEntity.getIncrease());
        tCrmAverageCarEntity.setCarNum(String.valueOf(carNum+(carNum*ins)-(carNum*loss)));
        //判断id存在不存在如果为null则是新增

        if (null ==tCrmAverageCarEntity.getId() || StringUtils.isEmpty(tCrmAverageCarEntity.getId())) {
           tCrmAverageCarEntity.setStatus("1");
            this.iAverageDao.saveOrUpdate(tCrmAverageCarEntity);
        } else {
            //如果有id则是更改
            this.iAverageDao.saveOrUpdate(tCrmAverageCarEntity);
        }
        //返回实体
        return tCrmAverageCarEntity;
    }

    @Override
    public Map info(String id) throws Exception {
        String sql = "select * from " + tabName + " where id = ? ";
        return this.iAverageDao.info(sql, id);
    }

    @Override
    public Map newPage(String start, String limit, String year) throws Exception {
        String sql = "select * from  T_CRM_AVERAGE_CAR where 1=1 ";
        List<Object> params = new ArrayList();
        if (!StringUtils.isEmpty(year)) {
            sql += "and year= ?";
            params.add(year);
        }
        return this.iAverageDao.page(sql, params.toArray(), start, limit);
    }
}
